package com.xiaoyu.lanling.widget.photo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import com.xiaoyu.base.app.AppContext;
import com.xiaoyu.base.app.GlobalUI;
import com.xiaoyu.base.image.ImageUrlManager;
import com.xiaoyu.base.net.OkHttpDownloader;
import com.xiaoyu.base.utils.RxUtils;

import java.io.File;
import java.io.FileNotFoundException;

import io.reactivex.Single;

public class PhotoUtils {

    @SuppressLint("CheckResult")
    public static void saveImageFromUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        downloadImage(url)
                .compose(RxUtils.ioToMainSingleScheduler())
                .subscribe(file -> {
                    if (file != null && file.exists()) {
                        AppContext.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                        GlobalUI.getInstance().showToast("保存成功 " + file.getPath());
                    } else {
                        GlobalUI.getInstance().showToast("保存失败：文件未找到");
                    }
                }, throwable -> {
                    if (throwable instanceof FileNotFoundException) {
                        GlobalUI.getInstance().showToast("保存失败：存储权限可能未赋予，请检查权限设置");
                    }
                    throwable.printStackTrace();
                });
    }

    public static Single<File> downloadImage(String url) {
        return Single.create(emitter -> {
            try {
                File imageFile = new File(Environment.getExternalStorageDirectory().toString()
                        + File.separator + "CPPictures" + File.separator + "cp_" + System.currentTimeMillis() + ".jpg");
                if (!imageFile.getParentFile().exists()) {
                    imageFile.getParentFile().mkdirs();
                }

                String tempUrl = url;
                if (tempUrl.contains(ImageUrlManager.NEWSNS_YIZHOUCP_IMAGE_DOMAIN) && tempUrl.contains(ImageUrlManager.HTTPS)) {
                    tempUrl = tempUrl.replace(ImageUrlManager.HTTPS, ImageUrlManager.HTTP);
                }

                OkHttpDownloader downloader = new OkHttpDownloader(tempUrl, imageFile.getPath());
                downloader.setDownloadStatusListener(new OkHttpDownloader.DownloadStatusListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess() {
                        emitter.onSuccess(imageFile);
                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }

                    @Override
                    public void onEnd() {

                    }

                    @Override
                    public void onCancel() {

                    }
                });
                downloader.download();
            } catch (Exception e) {
                emitter.onError(e);
                e.printStackTrace();
            }
        });
    }
}
